import re
from typing import Dict, List
import importlib.resources as pkg_resources


def parse_company_accounts_config(text: str) -> Dict[str, dict]:
    """
    解析公司与账户配置的文本，返回结构：
    {
      company_full_name: {
        "sheet_name": str,
        "accounts": [ {"bank_name": str, "account_number": str}, ... ]
      },
      ...
    }
    """
    companies: Dict[str, dict] = {}
    current_company: str | None = None
    sheet_name: str | None = None
    accounts: List[dict] = []

    lines = [ln.strip() for ln in text.splitlines()]
    for line in lines:
        if not line:
            continue
        if line.startswith("公司全称:"):
            # 保存上一公司块
            if current_company:
                companies[current_company] = {
                    "sheet_name": sheet_name or "",
                    "accounts": accounts,
                }
            # 开启新块
            current_company = line.split(":", 1)[1].strip()
            sheet_name = None
            accounts = []
        elif line.startswith("Sheet Name:"):
            sheet_name = line.split(":", 1)[1].strip()
        elif line.startswith("开户行:"):
            # 格式：开户行: XXX, 账号: YYY
            m = re.match(r"开户行:\s*(.+?)\s*,\s*账号:\s*(.+)$", line)
            if m:
                accounts.append({
                    "bank_name": m.group(1).strip(),
                    "account_number": m.group(2).strip(),
                })
        else:
            # 跳过标题行“所属账号和开户行:”等
            continue

    # 收尾
    if current_company:
        companies[current_company] = {
            "sheet_name": sheet_name or "",
            "accounts": accounts,
        }

    return companies


def load_company_accounts_config_file(file_path: str) -> Dict[str, dict]:
    with open(file_path, "r", encoding="utf-8") as f:
        text = f.read()
    return parse_company_accounts_config(text)


def load_company_accounts_from_package() -> Dict[str, dict]:
    """
    从打包的资源中加载 company_accounts.txt（路径：src/assets/templates）。
    使用 importlib.resources 确保 PyInstaller/zip 包中可读取。
    """
    from src.assets import templates as templates_pkg
    with pkg_resources.files(templates_pkg).joinpath("company_accounts.txt").open("r", encoding="utf-8") as f:
        text = f.read()
    return parse_company_accounts_config(text)


